/**
 * 订单生产
 * 
 * @return {}
 */
var orderProduce = new Ext.LoadMask(Ext.getBody(), {
			msg : "正在提交,请稍后..."
		});
var queryOrderProduceSearch = function() {
	var queryOrdersProduceFieldSet = new Ext.form.FieldSet({
		id : 'queryOrdersProduceFieldSet',
		title : '查询条件',
		collapsible : true,// 可折叠
		buttonAlign : 'center',
		keys : [{
					key : 13, // 13代表回车
					fn : queryOrdersProduce,
					scope : this
				}],
		items : [{
			layout : 'column',
			border : false,
			items : [{
						columnWidth : .25,
						layout : 'form',
						border : false,
						items : [{
									xtype : 'textfield',
									name : 'id',
									anchor : '100%',
									fieldLabel : '订单编号'
								}]
					}, {
						columnWidth : .25,
						layout : 'form',
						border : false,
						items : [{
									xtype : 'textfield',
									anchor : '100%',
									fieldLabel : '订单编码',
									name : "orderCode"
								}]
					}, {
						columnWidth : .25,
						layout : 'form',
						border : false,
						items : [{

							xtype : 'datefield',
							fieldLabel : '配送开始时间',
							editable : false,
							format : "Y-m-d",
							anchor : "100%",
							width : 175,
							id : 'produce_startDate',
							name : "deliveryDateStart",
							listeners : {
								'select' : function() {
									Ext.getCmp('produce_endDate')
											.setMinValue(this.getValue());
								}
							}

						}]
					}, {
						columnWidth : .25,
						layout : 'form',
						border : false,
						items : [{

							xtype : 'datefield',
							fieldLabel : '配送结束时间',
							editable : false,
							format : "Y-m-d",
							anchor : "100%",
							width : 175,
							id : 'produce_endDate',
							name : "deliveryDateEnd",
							listeners : {
								'select' : function() {
									Ext.getCmp('produce_startDate')
											.setMaxValue(this.getValue());
								}
							}

						}]
					}]
		}, {
			layout : 'column',
			border : false,
			items : [{
						columnWidth : .25,
						layout : 'form',
						border : false,
						items : [{
									xtype : 'dataDictionaryCmb',
									anchor : '100%',
									fieldLabel : "订单类型",
									editable : false,
									autoLoad : false,
									existall : true,
									defaultFirstRow : 1,
									hiddenName : 'orderType',
									dictionaryType : PmsUtil.order_type
								}]
					}, {
						columnWidth : .25,
						layout : 'column',
						border : false,
						items : [{
									text : '查询',
									xtype : 'button',
									width : 70,
									handler : function() {
										queryOrdersProduce();
									},
									style : {
										marginLeft : "100px",
										marginRight : "10px"
									}
								}, {
									text : '重置',
									xtype : 'button',
									width : 70,
									handler : function() {
										queryOrderProduceForm.getForm().reset();
									}
								}]
					}]
		}]
	});
	fieldSetListeners(['queryOrdersProduceFieldSet', 'queryOrderProduceForm',
					'orderManagerGrid'], [0.16, 0.84]);

	var queryOrderProduceForm = new Ext.form.FormPanel({
				id : 'queryOrderProduceForm',
				anchor : '100% 16%',
				frame : true,
				labelAlign : 'right',
				bodyBorder : false,
				items : [queryOrdersProduceFieldSet]
			});
	return queryOrderProduceForm;
};

/**
 * grids
 */
var orderProduceManagerGrid = function() {
	var orderProduceSm = new Ext.grid.CheckboxSelectionModel({
				checkOnly : true,
				renderer : function(v, p, record) {
					var orderStatus = record.get('orderStatus');
					if (orderStatus != PmsUtil.ORDER_STATUS_COMLETER) {
						return '<div class="x-grid3-row-checker">&#160;</div>';
					} else {
						return '';
					}
				},
				listeners : {
					beforerowselect : function(SelectionModel, rowIndex,
							keepExisting, record) {
						var orderStatus = record.get('orderStatus');
						if (orderStatus != PmsUtil.ORDER_STATUS_COMLETER) {
							return true;
						} else {
							return false;
						}
					}
				}
			});
	// 定义表的每列（对应表头信息）
	var orderProduceCm = new Ext.grid.ColumnModel([orderProduceSm, {
				dataIndex : "id",
				header : "订单编号",
				sortable : false,
				width : 60
			}, {
				dataIndex : "orderCode",
				header : "订单编码",
				sortable : false,
				width : 160,
				renderer : function(value, cellmeta, record, rowIndex,
						columnIndex, store) {
					var returnValue = "";
					var orderId = record.data.id;
					if (value) {
						returnValue = '<a href ="#" onClick="lookOrderProduceDetail(\''
								+ orderId + '\')">' + value + '</a>';
					}
					return returnValue;
				}
			}, {
				dataIndex : "deliveryDate",
				header : "配送日期",
				sortable : false,
				width : 80,
				renderer : function(date) {
					return '<font color=\"#FF0000\" >'
							+ Ext.util.Format.substr(date, 0, 10) + '</font>';
				}
			}, {
				dataIndex : "deliveryTimes",
				header : "配送时间段",
				sortable : false,
				width : 90,
				renderer : function(value) {
					return '<font color=\"#FF0000\" >' + value + '</font>';
				}
			}, {
				dataIndex : "orderType",
				header : "订单类型",
				sortable : false,
				width : 70,
				renderer : function(value) {
					return PmsUtil.OrderType(value);
				}
			}, {
				dataIndex : "orderStatus",
				header : "订单状态",
				sortable : false,
				width : 60,
				renderer : function(value) {
					if (value) {
						return '<font color=\"#FF0000\" >'
								+ PmsUtil.OrderStatus(value) + '</font>';
					}
				}
			}, {
				dataIndex : "payAmount",
				header : "订单金额",
				sortable : false,
				width : 70,
				renderer : function(value) {
					return Ext.util.Format.number(value, '0,0.00');
				}
			}, {
				dataIndex : "deliveryFee",
				header : "配送费用",
				sortable : false,
				width : 60,
				renderer : function(value) {
					return Ext.util.Format.number(value, '0,0.00');
				}
			}, {
				dataIndex : "goodsNumber",
				header : "商品数量",
				sortable : false,
				width : 60
			}, {
				dataIndex : "remark",
				header : "备注",
				sortable : false,
				width : 100,
				renderer : function(value, meta, record) {
					if (value) {
						meta.attr = 'ext:qtitle="备注:" ext:qtip="' + value + '"';
						return '<font color=\"#FF0000\" >' + value + '</font>';;
					}
				}
			}, {
				dataIndex : "birthdayCard",
				header : "生日卡片",
				sortable : false,
				width : 80,
				renderer : function(value) {
					if (value) {
						var div = '<div ext:qtitle="生日卡片:" ext:qtip="{0}">{0}</div>';
						return '<font color=\"#FF0000\" >'
								+ String.format(div, value) + '</font>';
					}
				}
			},  {
				dataIndex : "consignee",
				header : "收货人",
				sortable : false,
				width : 70
			}, {
				dataIndex : "consignPhone",
				header : "收货人电话",
				sortable : false,
				width : 100
			}, {
				dataIndex : "consignAddress",
				header : "收货人地址",
				sortable : false,
				width : 180,
				renderer : function(value, meta, record) {
					if (value) {
						meta.attr = 'ext:qtitle="收货人地址:" ext:qtip="' + value
								+ '"';
						return value;
					}
				}
			}, {
				dataIndex : "createdDate",
				header : "创建时间",
				sortable : false,
				width : 130
			}, {
				header : "管理",
				width : 350,
				dataIndex : "id",
				renderer : function(j, i, g, m, h) {
					var orderId = g.data.id;
					var orderStatus = g.data.orderStatus;
					var k = "";
					if (isGranted("orderProduce_热敏单个打印")) {
						k += '&nbsp;&nbsp;<a href="#" onclick="printThermalOrder('
								+ orderId + ')\">热敏打印</a>';
					}
					if (isGranted("orderProduce_订单打印")) {
						k += '&nbsp;&nbsp;<a href="#" onclick="printOrder('
								+ orderId + ')\">订单打印</a>';
					}
					if (isGranted("orderProduce_配送单打印")) {
						k += '&nbsp;&nbsp;<a href="#" onclick="printDeliveryOrder('
								+ orderId + ')\">配送单打印</a>';
					}
					if (orderStatus == 3 && isGranted("orderProduce_单个发货")) {
						k += '&nbsp;&nbsp;<a href="#" onclick="updateOrderProduceStatusOne('
								+ orderId
								+ ','
								+ "4"
								+ ','
								+ "'已发货'"
								+ ')\">订单发货</a>';
					}

					if (orderStatus == 3 && isGranted("orderProduce_填写物流单号")) {
						k += '&nbsp;&nbsp;<a href="#" onclick="addLogisticNo('
								+ orderId + ')\">填写物流单号</a>';
					}
					if (orderStatus == 3 && isGranted("orderProduce_修改订单")) {
						k += '&nbsp;&nbsp;<a href="#" onclick="updateOrderProduce('
								+ orderId + ')\">修改订单</a>';
					}
					return k;
				}
			}]);

	// 定义分析器
	var orderManagerReader = new Ext.data.JsonReader({
				totalProperty : "totalCount",
				root : "list",
				fields : [{
							name : "id"
						}, {
							name : "orderCode"
						}, {
							name : "userPaymentId"
						}, {
							name : "orderStatus"
						}, {
							name : "payStatus"
						}, {
							name : "payType"
						}, {
							name : "payDate"
						}, {
							name : "limitPayDate"
						}, {
							name : "totalAmount"
						}, {
							name : "goodsNumber"
						}, {
							name : "payAmount"
						}, {
							name : "deliveryDate"
						}, {
							name : "deliveryTimes"
						}, {
							name : "deliveryFee"
						}, {
							name : "isUserCoupon"
						}, {
							name : "couponId"
						}, {
							name : "couponFee"
						}, {
							name : "consignee"
						}, {
							name : "consignPhone"
						}, {
							name : "consignAddress"
						}, {
							name : "birthdayTitle"
						}, {
							name : 'logisticNo'
						}, {
							name : "birthdayCard"
						}, {
							name : "remark"
						}, {
							name : "payGoodsName"
						}, {
							name : "createdDate"
						}, {
							name : "createdName"
						}, {
							name : "orderType"
						}]
			});

	// 取数据store
	var orderProduceViewStore = new Ext.data.Store({
				autoLoad : true,// 要加载数据必须设置为true
				proxy : new Ext.data.HttpProxy({
							url : __ctxPath + "/orderManager/selectOrders"
						}),
				remoteSort : true,
				baseParams : {
					start : 0,
					limit : 25,
					orderStatus : '3'
				},
				listeners : {
					beforeload : {
						fn : function(thiz, options) {
							Ext.apply(thiz.baseParams, Ext
											.getCmp('queryOrderProduceForm')
											.getForm().getValues());
						}
					}
				},
				reader : orderManagerReader
			});
	orderProduceViewStore.setDefaultSort("od.confirmed_date", "desc");
	var orderProduceTb = new Ext.Toolbar({// 定义grid的toolbar
		height : 25,
		items : []
	});
	orderProduceTb.add(new Ext.scm.Button({
				text : "批量发货",
				width : 80,
				hsValue : 'orderProduce_批量发货',
				pressed : true,
				iconCls : "btn-edit",
				handler : function() {
					batchOrderProduceUpdateStatus(4, '已发货');
				}
			}));
	orderProduceTb.add(new Ext.Toolbar.Spacer());
	orderProduceTb.add(new Ext.scm.Button({
				text : "热敏打印",
				width : 80,
				hsValue : 'orderProduce_热敏批量打印',
				pressed : true,
				iconCls : "btn-print",
				handler : function() {
					batchPrintThermalOrder();
				}
			}));
	orderProduceTb.add(new Ext.scm.Button({
				text : "配送单打印",
				width : 90,
				hsValue : 'orderProduce_配送单批量打印',
				pressed : true,
				iconCls : "btn-print",
				handler : function() {
					batchPrintDeliveryOrder();
				}
			}));
	orderProduceTb.add(new Ext.Toolbar.Spacer());
	orderProduceTb.add(new Ext.scm.Button({
				text : "交接单打印",
				width : 80,
				hsValue : 'orderProduce_交接单打印',
				pressed : true,
				iconCls : "btn-print",
				handler : function() {
					batchPrintHandOverOrderComfirmed();
				}
			}));

	orderProduceTb.add(new Ext.Toolbar.Spacer());
	orderProduceTb.add(new Ext.scm.Button({
				text : "刷 新",
				width : 80,
				hsValue : 'orderProduce_刷新',
				iconCls : "btn-refresh",
				pressed : true,
				handler : function() {
					queryOrdersProduce();
				}
			}));
	var orderProduceManagerGrid = new Ext.grid.GridPanel({
				id : 'orderProduceManagerGrid',
				store : orderProduceViewStore,
				cm : orderProduceCm,
				sm : orderProduceSm,
				autoScroll : true,
				loadMask : true,
				stripeRows : true,
				columnLines : true,
				loadMask : {
					msg : "正在加载数据，请稍侯……"
				},
				viewConfig : {
					emptyText : '没有您想要的数据!'
				},
				anchor : '100% 84%',
				frame : true,
				tbar : orderProduceTb,
				bbar : new PG.PagingBar({
							id : 'orderProduceGridPage',
							store : orderProduceViewStore
						})
			});
	return orderProduceManagerGrid;
};

// 查询
function queryOrdersProduce() {
	if (Ext.getCmp('queryOrderProduceForm').getForm().isValid()) {
		var grid = Ext.getCmp('orderProduceManagerGrid');
		var store = grid.store;
		var pagesize = Ext.getCmp('orderProduceGridPage').pageSize;
		store.load({
					params : {
						start : 0,
						limit : pagesize,
						"orderStatusArray" : '3'
					}
				});
	}
}

/**
 * 订单单个发货
 * 
 * @param {}
 *            orderId
 * @param {}
 *            orderStatus
 * @param {}
 *            statusName
 */
function updateOrderProduceStatusOne(orderId, orderStatus, statusName) {
	Ext.Msg.confirm("信息确认", "您确定要将订单状态变更为<span style='color:#F00'>"
					+ statusName + "</span>？", function(c) {
				if (c == "yes") {
					commonOrderProduceUpateOrder(orderId, orderStatus,
							statusName);
				}
			});
}

/**
 * 查询订单详情
 * 
 * @param {}
 *            id
 */
function lookOrderProduceDetail(id) {
	var centerPanel = App.getContentPanel();
	var tab = centerPanel.getItem(PmsUtil.ORDER_MESSAGE_DETAIL);
	var createNewTab = new CreatNewTab(PmsUtil.ORDER_MESSAGE_DETAIL, '订单详情');
	if (tab == null) {
		createNewTab.createNew(tab);
	} else {
		createNewTab.createOld(tab, ['lookOrderDetailFields',
						'lookOrderDetailForm', 'lookOrderDetailGrid']);
	}
	Ext.Loader.load([__ctxPath + '/js/order/orderDetail.js'], function() {
				Ext.getCmp("centerTabPanel").getActiveTab().add(
						lookOrderDetailSearch(id), orderDetailGrid(id));
				Ext.getCmp("centerTabPanel").getActiveTab().doLayout();
			});
}

/**
 * 批量修改订单状态
 */
function batchOrderProduceUpdateStatus(orderStatus, statusName) {
	var d = Ext.getCmp("orderProduceManagerGrid");
	var jsonrecord = d.getSelectionModel().getSelections();
	if (jsonrecord.length == 0) {
		Ext.MessageBox.show({
					title : "操作信息",
					msg : "请选择要发货的订单!",
					buttons : Ext.MessageBox.OK,
					icon : Ext.MessageBox.WARNING
				});
		return;
	}
	Ext.Msg.confirm("信息确认", "您确定要将订单状态变更为<span style='color:#F00'>"
					+ statusName + "</span>？", function(c) {
				if (c == "yes") {
					var orderIds = "";
					var m = 0;
					for (var i = 0; i < jsonrecord.length; i++) {
						var tmp = jsonrecord[i];
						if (m > 0) {
							orderIds = orderIds + "," + tmp.data.id;
						} else {
							orderIds = tmp.data.id;
						}
						m++;
					}
					commonOrderProduceUpateOrder(orderIds, orderStatus,
							statusName);
				}
			});
}

/**
 * 公用修改订单状态方法
 * 
 * @param {}
 *            orderIds
 * @param {}
 *            orderStatus
 * @param {}
 *            statusName
 */
function commonOrderProduceUpateOrder(orderIds, orderStatus, statusName) {
	orderProduce.show();
	Ext.Ajax.request({
				url : __ctxPath + "/orderManager/updateOrderStatus",
				params : {
					orderIds : orderIds,
					orderStatus : orderStatus,
					statusName : statusName,
					cancelReason : ''
				},
				method : "post",
				success : function(response, config) {
					orderProduce.hide();
					var jsonData = Ext.util.JSON.decode(response.responseText);
					if (jsonData.success) {
						Ext.MessageBox.show({
									title : "信息提示",
									msg : "修改订单状态成功!",
									buttons : Ext.MessageBox.OK,
									icon : Ext.MessageBox.INFO
								});
						queryOrdersProduce();
					} else {
						Ext.MessageBox.show({
									title : "操作信息",
									msg : "修改订单状态失败!",
									buttons : Ext.MessageBox.OK,
									icon : Ext.MessageBox.ERROR
								});
					}
				},
				failure : function(response, config) {
					orderProduce.hide();
					Ext.MessageBox.show({
								title : "错误提示",
								msg : "服务器请求异常，请稍后再试!",
								buttons : Ext.MessageBox.OK,
								icon : Ext.MessageBox.ERROR
							});
				}
			});
}

/**
 * 填写物流单号
 * 
 * @param {}
 *            orderId
 */
function addLogisticNo(orderId) {
	try {
		addLogisticNoWindows(orderId).show();
	} catch (Error) {
		Ext.Loader.load([__ctxPath + '/js/order/logisticNo.js'], function() {
					addLogisticNoWindows(orderId).show();
				});
	}

}

/**
 * 订单打印
 * 
 * @param {}
 *            orderId
 */
function printOrder(orderId) {
	window.open(__ctxPath + "/orderManager/printOrder?orderId=" + orderId,
			"_blank");
}
/**
 * 订单热敏打印
 * 
 * @param {}
 *            orderId
 */
function printThermalOrder(orderId) {
	window.open(__ctxPath + "/orderManager/printThermalOrder?orderId="
					+ orderId, "_blank");
}

/**
 * 批量热敏打印
 */
function batchPrintThermalOrder() {
	var d = Ext.getCmp("orderProduceManagerGrid");
	var jsonrecord = d.getSelectionModel().getSelections();
	if (jsonrecord.length == 0) {
		Ext.MessageBox.show({
					title : "操作信息",
					msg : "请选择要打印的订单!",
					buttons : Ext.MessageBox.OK,
					icon : Ext.MessageBox.WARNING
				});
		return;
	}
	Ext.Msg.confirm("信息确认", "您确定要打印选中订单吗？", function(c) {
				if (c == "yes") {
					var orderIds = "";
					var m = 0;
					for (var i = 0; i < jsonrecord.length; i++) {
						var tmp = jsonrecord[i];
						if (m > 0) {
							orderIds = orderIds + "," + tmp.data.id;
						} else {
							orderIds = tmp.data.id;
						}
						m++;
					}
					printThermalOrder(orderIds);
				}
			});
};

// 配送单打印
function batchPrintDeliveryOrder() {
	var d = Ext.getCmp("orderProduceManagerGrid");
	var jsonrecord = d.getSelectionModel().getSelections();
	if (jsonrecord.length == 0) {
		Ext.MessageBox.show({
					title : "操作信息",
					msg : "请选择要打印的订单!",
					buttons : Ext.MessageBox.OK,
					icon : Ext.MessageBox.WARNING
				});
		return;
	}

	var orderIds = "";
	var m = 0;
	for (var i = 0; i < jsonrecord.length; i++) {
		var tmp = jsonrecord[i];
		if (m > 0) {
			orderIds = orderIds + "," + tmp.data.id;
		} else {
			orderIds = tmp.data.id;
		}
		m++;
	}
	printDeliveryOrder(orderIds);
};

// 单个配送单打印
function printDeliveryOrder(orderIds) {
	window.open(__ctxPath + "/orderManager/printDeliveryOrder?orderIds="
					+ orderIds, "_blank");
}

// 修改
function updateOrderProduce(orderId) {
	try {
		updateOrderWin(orderId, 'orderProduceManagerGrid').show();
	} catch (Error) {
		Ext.Loader.load([__ctxPath + '/js/order/orderForm.js'], function() {
					updateOrderWin(orderId, 'orderProduceManagerGrid').show();
				});
	}
}


// 交接单打印
function batchPrintHandOverOrderComfirmed() {
	var d = Ext.getCmp("orderProduceManagerGrid");
	var jsonrecord = d.getSelectionModel().getSelections();
	if (jsonrecord.length == 0) {
		Ext.MessageBox.show({
					title : "操作信息",
					msg : "请选择要打印的订单!",
					buttons : Ext.MessageBox.OK,
					icon : Ext.MessageBox.WARNING
				});
		return;
	}

	var orderIds = "";
	var m = 0;
	for (var i = 0; i < jsonrecord.length; i++) {
		var tmp = jsonrecord[i];
		if (m > 0) {
			orderIds = orderIds + "," + tmp.data.id;
		} else {
			orderIds = tmp.data.id;
		}
		m++;
	}
	window.open(__ctxPath + "/orderManager/printHandOverOrderComfirmed?orderIds="
					+ orderIds, "_blank");
};

Ext.getCmp("centerTabPanel").getActiveTab().add(queryOrderProduceSearch(),
		orderProduceManagerGrid());
Ext.getCmp("centerTabPanel").getActiveTab().doLayout();